package com.cyz.mobile;


import java.math.BigDecimal;
import java.util.Collection;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.demo.annotation.LoginFilter;
import com.demo.annotation.MobileMethod;
import com.demo.mobile.MobException;
import com.demo.mobile.MobileInfo;
import com.demo.service.MobileVerifyService;
import com.demo.validator.MobileLoginValidate;
import com.shopcart.domain.Store;
import com.shopcart.domain.StoreGoods;
import com.shopcart.service.OrderService;
import com.vsd.domain.StoreTable;
import com.vsd.mobile.error.MEnumError;
import com.vsd.repository.StoreTableRepository;
import com.vsd.service.CodeService;
import com.vsd.service.StoreGoodsService;
import com.vsd.service.StoreService;
import com.zy.account.proto.MUserAccount.MAccount;
import com.zy.order.proto.MSOrder.MDiscount;
import com.zy.order.proto.MSOrder.MGoodsCart;
import com.zy.order.proto.MSOrder.MGoodsCartList;
import com.zy.pad.proto.MPadOrder.MTable;
import com.zy.pad.proto.MPadOrder.MTableList;
import com.zy.sys.proto.MOCommon.MRetEx;

@Controller
@RequestMapping("/mobile/")
public class MiPadController {
	
	@Autowired
	private StoreService storeService;
	@Autowired
	private MobileVerifyService mobileVerifyService;
	@Autowired
	private StoreTableRepository storeTableRepository;
	@Autowired
	private StoreGoodsService storeGoodsService;
	@Autowired
	private CodeService codeService;
	@Autowired
	private OrderService orderService;
	
	
	/**
	@api mPadLogin mPadLogin	//pad端 登录接口
	@return MAccount
	*/
	@RequestMapping("/mPadLogin")
	@MobileMethod
	public MAccount.Builder mPadLogin(MobileInfo mobileInfo,String account, String password, String device, String cid) throws Exception {
		// 参数校验
		if (StringUtils.isBlank(account)) {
			throw new MobException("account");
		}
		if (StringUtils.isBlank(password)) {
			throw new MobException("password");
		}
		if (StringUtils.isBlank(device)) {
			throw new MobException("device");
		}
				
		//校验登录
		Store user = storeService.findByAccountAndPassword(account, password);
		
		if(user==null){
			throw new MobException(MEnumError.LOGIN_FAILURE_ERROR);
		}
		 
		//禁用
		if(user.getIsOnline() == 0){
			throw new MobException(MEnumError.ACCOUNT_STOP_ERROR);
		}
		
		mobileInfo.setUserid(user.getId()+"");
		String verify = mobileVerifyService.updateMobileVerify(mobileInfo, device, cid, true);
		
		// 返回
		MAccount.Builder ret = MAccount.newBuilder();
		ret.setId(user.getId()+"");
		ret.setVerify(verify);
		return ret;	
	}
	
	/**
	@api mPostPadOrder mPostPadOrder			//生成pad端订单（登录）
	@param required MGoodsCartList cart			//购物篮（info 存放第几桌）
	@return MRetEx //code 0 成功 title 订单价格 msg 订单号  
	*/
	@RequestMapping("/mPostPadOrder")
	@MobileMethod(reqClz=MGoodsCartList.class)
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MRetEx.Builder mPostPadOrder(MobileInfo mobileInfo,MGoodsCartList.Builder requestProto) throws Exception {
		// 参数校验
		if(requestProto==null||requestProto.getListCount()==0) throw new MobException("cart");
		return orderService.postPadOrder(requestProto,mobileInfo.getUserid());
	}
	
	/**
	@api mTables mTables	//桌号列表（登录）
	@return MTableList
	*/
	@RequestMapping("/mTables")
	@MobileMethod
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MTableList.Builder mTables(MobileInfo mobileInfo) throws Exception {
		
		Collection<StoreTable> list =   storeTableRepository.findByStoreId(mobileInfo.getUserid(), new Sort(Direction.DESC, "sort"));
		// 返回
		MTableList.Builder ret = MTableList.newBuilder();
		for (StoreTable t : list) {
			MTable.Builder tb = MTable.newBuilder();
			tb.setId(t.getId());
			tb.setName(t.getName());
			tb.setState(1);
			ret.addTables(tb);
		}
		return ret;	
	}
	
	/**
	@api mGetPadCoupon mGetPadCoupon			//pad端 获取优惠信息()
	@param required MGoodsCartList cart			//购物篮 
	@return MDiscount
	*/
	@RequestMapping("/mGetPadCoupon")
	@MobileMethod(reqClz=MGoodsCartList.class)
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MDiscount.Builder mGetPadCoupon(MobileInfo mobileInfo,MGoodsCartList.Builder requestProto,String couponId) throws Exception {
		if(requestProto==null||requestProto.getListCount()==0) throw new MobException("cart");
		MDiscount.Builder ret = MDiscount.newBuilder();
		
		String storeId = mobileInfo.getUserid();
		BigDecimal total = BigDecimal.ZERO;
		BigDecimal totalWine = BigDecimal.ZERO;
		BigDecimal winNeed = BigDecimal.ZERO;//需支付酒水
		for (MGoodsCart cart : requestProto.getListList()) {
			StoreGoods g = storeGoodsService.findById(cart.getId());
			if(g==null) throw new MobException(MEnumError.ORDER_GOODS_NOT_EXIST);
			if(g.getType()==2) throw new MobException(MEnumError.ONLY_DISH_ALLOW);
			if(g.getType()==3){
				totalWine = totalWine.add(g.getNowPrice().multiply(new BigDecimal(cart.getNum())));
			}else{
				total = total.add(g.getNowPrice().multiply(new BigDecimal(cart.getNum())));
			}
		}
		
		Store store = storeService.findById(storeId);
		if(store==null) throw new MobException(MEnumError.STORE_NOT_FOUND);
		Integer wineRate = store.getWineRate();
		if(store.getWineRate()==null){
			wineRate = new Integer(codeService.getWineRate());
		}
		
		//可减免酒水
		BigDecimal wineDis = BigDecimal.ZERO;
		if(total.floatValue()>store.getWineBegin()){
			wineDis = total.multiply(new BigDecimal(wineRate)).divide(BigDecimal.valueOf(1000),0);
		}
		
		//酒水全部减免
		if(totalWine.compareTo(wineDis)<0){
			wineDis = totalWine;
		}else{
			winNeed = totalWine.subtract(wineDis);
		}
		ret.setInfo("满"+store.getWineBegin()+"元，送"+store.getWineBegin()*wineRate/1000+"元酒水");
		ret.setFull(store.getWineBegin()+"");
		ret.setDiscount(wineDis.toString());
		ret.setDisc(wineRate+"");
		ret.setTotal(total.add(winNeed).toString());
		return ret;
	}
	
}
